package Offer.offer2019;

/**
 * 打印1到最大的n位数
 *
 * @author: leiwenkang02@meituan.com
 * @date: 2019/4/24
 * @time: 22:30
 */
public class Offer12 {

    public static void main(String[] args) {
        Offer12 offer12 = new Offer12();
        offer12.print1toN(3);
    }

    /**
     * 方法一：考虑大数问题，采用数组模拟加法
     *
     * @param n
     */
    public void print1toN(int n) {
        if (n <= 0) {
            return;
        }
        int[] array = new int[n];
        while (add(array)) {
            printArray(array);
        }

    }

    private boolean add(int[] array) {
        int takeOver = 0;
        for (int i = array.length - 1; i >= 0; i--) {
            int sum = array[i] + takeOver;
            if (i == array.length - 1) {
                sum++;
            }
            if (sum < 10) {
                array[i] = sum;
                return true;
            } else {
                if (i == 0) {
                    return false;
                }
                sum -= 10;
                array[i] = sum;
                takeOver = 1;
            }
        }
        return true;
    }

    /**
     * 打印array数组，注意数组前面为0的要去掉
     * @param array
     */
    private void printArray(int[] array) {
        if (array == null || array.length == 0){
            return;
        }
        boolean isPrint = false;
        for (int i = 0; i < array.length; i++) {
            if (array[i] != 0) {
               isPrint = true;
            }
            if (isPrint) {
                System.out.print(array[i]);
            }
        }
        System.out.println();
    }


    /**
     * 方法二：递归思路
     *
     * @param n
     */
    public void print1toN2(int n) {
        if (n <= 0) {
            return;
        }
        int[] array = new int[n];
        print1toN2(array, 0);
    }

    private void print1toN2(int[] array, int index) {
        if (index == array.length) {
            printArray(array);
            return;
        }
        for (int i = 0; i < 10; i++) {
            array[index] = i;
            print1toN2(array, index + 1);
        }
    }

}
